<template>
    <div class="add-fuel-expense-page">
        <div class="page-title">新增油费</div>

        <div class="form card">
            <div class="form-item required">
                <label class="label">车牌号：</label>
                <select class="input" v-model="form.licensePlateNumber">
                    <option value="" disabled>请选择车牌号</option>
                    <option v-for="p in vehicleOptions" :key="p" :value="p">{{ p }}</option>
                </select>
            </div>

            <div class="form-item required">
                <label class="label">加油费用/元：</label>
                <input class="input" type="number" min="0" v-model.number="form.fuelCost" placeholder="请输入加油费用" />
            </div>

            <div class="form-item required">
                <label class="label">加油量/L：</label>
                <input class="input" type="number" min="0" v-model.number="form.fuelQuantity" placeholder="请输入加油量" />
            </div>

            <div class="form-item required">
                <label class="label">起始公里数：</label>
                <input class="input" type="number" min="0" v-model.number="form.startMileage" placeholder="请输入起始公里数" />
            </div>

            <div class="form-item required">
                <label class="label">支付方式：</label>
                <div class="radios">
                    <label class="radio"><input type="radio" value="微信支付" v-model="form.paymentMethod" /> 微信支付</label>
                    <label class="radio"><input type="radio" value="支付宝支付" v-model="form.paymentMethod" /> 支付宝支付</label>
                    <label class="radio"><input type="radio" value="银联支付" v-model="form.paymentMethod" /> 银联支付</label>
                    <label class="radio"><input type="radio" value="企业转账" v-model="form.paymentMethod" /> 企业转账</label>
                    <label class="radio"><input type="radio" value="线下支付" v-model="form.paymentMethod" /> 线下支付</label>
                    <label class="radio">
                        <input type="radio" value="其它" v-model="form.paymentMethod" /> 其它
                    </label>
                    <input class="input other-input" :disabled="form.paymentMethod !== '其它'"
                        v-model.trim="form.otherPaymentMethod" placeholder="请输入其它支付方式" />
                </div>
            </div>

            <div class="form-item required">
                <label class="label">经办人：</label>
                <input class="input" v-model.trim="form.handler" placeholder="请输入经办人" />
            </div>

            <div class="form-item">
                <label class="label">备注：</label>
                <textarea class="textarea" v-model.trim="form.remarks" placeholder="请输入备注"></textarea>
            </div>

            <div class="form-actions">
                <button class="btn primary" :disabled="submitting" @click="handleSubmit">提交</button>
                <button class="btn" @click="handleCancel">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { read, write } from '@/assets/Axios/axiosHttple'

interface CreateFuelExpenseDto {
    licensePlateNumber: string
    fuelCost: number
    fuelQuantity: number
    startMileage: number
    paymentMethod: string
    otherPaymentMethod: string
    handler: string
    remarks: string
    createdBy: string
}

const form = reactive<CreateFuelExpenseDto>({
    licensePlateNumber: '',
    fuelCost: 0,
    fuelQuantity: 0,
    startMileage: 0,
    paymentMethod: '',
    otherPaymentMethod: '',
    handler: '',
    remarks: '',
    createdBy: localStorage.getItem('username') || '张三'
})

const submitting = ref(false)
const vehicleOptions = ref<string[]>([])

async function loadVehiclePlates() {
    const candidates: string[] = []
    const collect = (arr: any[]) => {
        for (const it of arr) {
            const plate = it?.plateNumber ?? it?.licensePlateNumber ?? it?.plate_no ?? it?.plateNo ?? it?.numberPlate
            if (plate) candidates.push(String(plate))
        }
    }
    const tryRead = async (params: any) => {
        try {
            const res = await read.get('baseinforead/api/VehicleManagement/GetVehicleList', { params })
            const d = res?.data
            const list: any[] = d?.data?.data || d?.data?.items || d?.data || []
            if (Array.isArray(list)) collect(list)
        } catch { }
    }
    await tryRead({ PageIndex: 1, PageSize: 200 })

    vehicleOptions.value = Array.from(new Set(candidates))
}

function validate(): string | null {
    if (!form.licensePlateNumber) return '请输入车牌号'
    if (form.fuelCost === null || form.fuelCost <= 0) return '请输入正确的加油费用'
    if (form.fuelQuantity === null || form.fuelQuantity <= 0) return '请输入正确的加油量'
    if (form.startMileage === null || form.startMileage < 0) return '请输入正确的起始公里数'
    if (!form.paymentMethod) return '请选择支付方式'
    if (form.paymentMethod === '其它' && !form.otherPaymentMethod) return '请输入其它支付方式'
    if (!form.handler) return '请输入经办人'
    return null
}

async function handleSubmit() {
    const msg = validate()
    if (msg) return window.alert ? (window.alert(msg), undefined) : undefined

    submitting.value = true
    try {
        const payload: CreateFuelExpenseDto = { ...form }
        const res = await write.post('baseinfowrite/api/FuelExpenses/Create', payload)
        const d = res?.data
        if (res?.status === 200 && (d?.code === 200 || d?.data === true || typeof d?.data === 'number')) {
            alert('添加成功')
            window.location.href = '/GetFuelExpenses?refresh=1'
        }
    } catch (e: any) {
        // 可在此接入全局消息组件
    } finally {
        submitting.value = false
    }
}

function handleCancel() {
    // 返回上一页或清空
    if (window.history.length > 1) {
        window.history.back()
    } else {
        // 单页场景下清空
        form.licensePlateNumber = ''
        form.fuelCost = 0
        form.fuelQuantity = 0
        form.startMileage = 0
        form.paymentMethod = ''
        form.otherPaymentMethod = ''
        form.handler = ''
        form.remarks = ''
        form.createdBy = localStorage.getItem('username') || '张三'
    }
}

onMounted(() => {
    loadVehiclePlates()
})
</script>

<style scoped>
.add-fuel-expense-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.form {
    padding: 16px;
    max-width: 720px;
}

.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 14px;
}

.form-item.required .label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

.label {
    width: 120px;
    color: #666;
}

.input {
    flex: 1;
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
}

.textarea {
    flex: 1;
    min-height: 90px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 10px;
}

.radios {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px 16px;
}

.radio {
    color: #606266;
}

.other-input {
    width: 200px;
}

.form-actions {
    margin-top: 18px;
    display: flex;
    gap: 10px;
}

.btn {
    height: 32px;
    padding: 0 16px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
